package job

import (
	"context"
	"time"
	"webook/payment/events"
	"webook/payment/service/wechat"
	"webook/pkg/logger"
)

type ProcessLocalEventsJob struct {
	l        logger.LoggerV1
	svc      *wechat.NativePaymentService
	producer events.Producer
}

func NewProcessLocalEventsJob(l logger.LoggerV1, svc *wechat.NativePaymentService, producer events.Producer) *ProcessLocalEventsJob {
	return &ProcessLocalEventsJob{l: l, svc: svc, producer: producer}
}

func (s *ProcessLocalEventsJob) Name() string {
	return "process_local_events"
}

func (s *ProcessLocalEventsJob) Run() error {
	offset := 0
	const limit = 100
	for {
		ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
		res, err := s.svc.FindInitLocalEvents(ctx, offset, limit)
		cancel()
		if err != nil {
			s.l.Error("查询本地消息表里待处理任务失败", logger.Error(err), logger.Int("offset", offset))
			return err
		}

		for _, elem := range res {
			//发送消息
			ctx1, cancel1 := context.WithTimeout(context.Background(), time.Second)
			err = s.producer.ProducePaymentEvent(ctx1, events.PaymentEvent{
				BizTradeNO: elem.BizTradeNO,
				Status:     uint8(elem.BizStatus),
			})
			cancel1()
			flag := true
			if err != nil {
				//考虑告警机制
				s.l.Error("本地消息表重发失败", logger.Error(err), logger.String("业务id", elem.BizTradeNO))
				flag = false
			}
			//更新数据库状态
			ctx2, cancel2 := context.WithTimeout(context.Background(), time.Second)
			er := s.svc.UpdateLocalEvent(ctx2, elem.BizTradeNO, flag)
			cancel2()
			if er != nil {
				s.l.Error("本地消息表更改状态失败", logger.Error(err), logger.String("业务id", elem.BizTradeNO), logger.Bool("任务状态", flag))
			}
		}
	}
}
